package com.faxsun.admin.controller;

import javax.annotation.Resource;

import org.broadleafcommerce.openadmin.web.controller.AdminAbstractController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.faxsun.model.response.Response;
import com.faxsun.model.response.result.QueryPaymentResult;
import com.faxsun.payment.service.gateway.PaySSSHostedGatewayService;
import com.faxsun.payment.service.gateway.PaymentGatewayConstants;

@Controller
@RequestMapping("/" + PaymentAdminController.SECTION_KEY)
public class PaymentAdminController extends AdminAbstractController {

	protected static final String SECTION_KEY = "payment";
	protected static String defaultQueryView = "modules/defaultContainer";

	@Resource(name = "fsPaySSSHostedGatewayService")
	protected PaySSSHostedGatewayService paySSSHostedGatewayService;

	@RequestMapping(value = "/querypay", method = RequestMethod.GET)
	public String initQuery(Model model) {

		model.addAttribute("viewType", "querypay");
		setModelAttributes(model, SECTION_KEY + "/querypay");
		return defaultQueryView;
	}

	/**
	 * 付款状态： 0:处理中，1:付款完成，2:付款失败
	 */
	@RequestMapping(value = "/querypay", method = RequestMethod.POST)
	public String queryHostPaymentStatus(@RequestParam(value = "orderId") long orderId, Model model) {
		Response<QueryPaymentResult> paymentResult = paySSSHostedGatewayService
				.queryPaymentResultByOrderId(orderId);
		if (paymentResult != null) {
			if (paymentResult.getResult() == null) {
				model.addAttribute("paymentResult", "订单未提交到支付系统");

			} else {
				switch (paymentResult.getResult().getStatus()) {

				case PaymentGatewayConstants.PAYMENT_RESULT_PROCESSING:
					model.addAttribute("paymentResult", "支付处理中");
					break;

				case PaymentGatewayConstants.PAYMENT_RESULT_SUCCESS:
					model.addAttribute("paymentResult", "支付成功");
					break;

				case PaymentGatewayConstants.PAYMENT_RESULT_FAIL:
					model.addAttribute("paymentResult", "支付失败");
					break;

				default:
					model.addAttribute("paymentResult", "无法确定");
					break;
				}
			}
		} else {
			model.addAttribute("paymentResult", "订单号 " + orderId + " 不存在");
		}

		model.addAttribute("viewType", "querypay");
		setModelAttributes(model, SECTION_KEY + "/querypay");
		return defaultQueryView;
	}
}
